package com.ja.openchat.ui.contact;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.FragmentGroupListChildBinding;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.viewmodels.GroupListChildViewModel;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.contact.Section;
import com.zy.openchat.core.model.contact.SectionInfo;
import com.zy.openchat.core.model.group.SuperGroupInfo;
import com.zy.openchat.core.model.message.ChatInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.goldze.mvvmhabit.base.BaseFragment;

public class GroupListChildFragment extends BaseFragment <FragmentGroupListChildBinding, GroupListChildViewModel> {

    public GroupListAdapter groupListAdapter;
    private List<Section> sectionList = new ArrayList<>();
    private int type;


    public static GroupListChildFragment newInstance(@IntRange(from = 0, to = 1) int type) {
        GroupListChildFragment fragment = new GroupListChildFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void initParam() {
        super.initParam();
        Bundle arguments = getArguments();
        if (arguments != null) {
            type = arguments.getInt("type");
        }
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_group_list_child;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initView() {
        super.initView();
        viewModel.setFragment(this);
        //初始化列表
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(layoutManager);
        groupListAdapter = new GroupListAdapter(R.layout.adapter_contact_list, R.layout.adapter_section_contact_list, sectionList);
        binding.recyclerView.setAdapter(groupListAdapter);
        //加载数据
        reloadGroups();
        //索引事件
        binding.slide.setOnIndexChangedListener((index, position) -> {
            for (int i = 0; i < sectionList.size(); i++) {
                if (sectionList.get(i).isHeader()) {
                    SectionInfo info = (SectionInfo) sectionList.get(i).getObject();
                    if (info.title.equals(String.valueOf(index.charAt(0)))) {
                        binding.recyclerView.scrollToPosition(i);
                        break;
                    }
                }
            }
        });
        //点击事件
        groupListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (sectionList != null && sectionList.size() > 0 && position >= 0 && position < sectionList.size()) {
                    Object obj = sectionList.get(position).getObject();
                    if (obj instanceof ChatInfo)
                        ChatActivity.startActivity(getContext(), (ChatInfo) obj);
                }
            }
        });
    }
    private Disposable handleDisposable = null;
    public void reloadGroups() {
        if(handleDisposable!=null&&!handleDisposable.isDisposed()){
            handleDisposable.dispose();
        }
        sectionList.clear();
        //获取联系人
        List<ChatInfo> list = TelegramManager.getTelegramManager().getTgData().getMyGroups();
        List<Observable<Section>> observables = new ArrayList<>();
        for (ChatInfo chatInfo : list) {
            observables.add(new Observable<Section>() {
                @Override
                protected void subscribeActual(Observer<? super Section> observer) {
                    TelegramManager.getTelegramManager().getSuperGroupInfo(getContext(), chatInfo.superGroupId(), new TgResultBlock<SuperGroupInfo>() {
                        @Override
                        public void onResult(Map<String, Object> request, JsonObject response, SuperGroupInfo obj) {
                            if (obj != null&&obj.status!=null) {
                                if(type==0){
                                    if(obj.status.isMyManageGroup()){
                                        observer.onNext(new Section(false, chatInfo));
                                    }
                                }else{
                                    if(obj.status.isMyJoinGroup()){
                                        observer.onNext(new Section(false, chatInfo));
                                    }
                                }
                            }
                            observer.onComplete();
                        }

                        @Override
                        public void onTimeout(Map<String, Object> request) {
                            observer.onComplete();
                        }
                    });
                }
            });
        }

        Observable.merge(observables)
                .subscribe(new Observer<Section>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        handleDisposable = d;
                    }

                    @Override
                    public void onNext(Section section) {
                        sectionList.add(section);
                        groupListAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //刷新定时器，防止短时间内大量refresh ui事件
    private Timer timerRefreshTask = null;

    public void startRefreshTimer() {
        if (timerRefreshTask == null) {
            timerRefreshTask = new Timer();
            timerRefreshTask.schedule(new TimerTask() {
                @Override
                public void run() {
                    binding.recyclerView.post(new Runnable() {
                        @Override
                        public void run() {
                            stopRefreshTimer();
                            reloadGroups();
                        }
                    });
                }
            }, 100);
        }
    }

    public void stopRefreshTimer() {
        if (timerRefreshTask != null) {
            timerRefreshTask.cancel();
            timerRefreshTask = null;
        }
    }

}
